package com.xyhuo.leetcode.december;

/**
 * 外观数列
 * https://leetcode.cn/problems/count-and-say/
 *
 * @time 2023/12/13
 */
public class CountAndSay {

//    public static void main(String[] args) {
//        CountAndSay cas = new CountAndSay();
//        String s = cas.countAndSay(6);
//        System.out.println(s);
//    }

    public String countAndSay(int n) {
        String[] dp = new String[n];
        dp[0] = "1";
        for (int i = 1; i < n; i++) {
            char[] charArray = dp[i - 1].toCharArray();
            int len = charArray.length;
            int count = 0;
            char last = charArray[0];
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < len; j++) {
                if (charArray[j] == last) {
                    count++;
                } else {
                    sb.append(count);
                    sb.append(last);
                    count = 1;
                    last = charArray[j];
                }
            }
            if (count != 0) {
                sb.append(count);
                sb.append(charArray[len - 1]);
            }
            dp[i] = sb.toString();
        }
        return dp[n - 1];
    }
}
